<template>
  <div class="container">
    <div style="padding: 20px">
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="用户名" prop="account">
          <el-input
            v-model="queryParams.account"
            placeholder="请输入用户名"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>

        <el-form-item label="姓名" prop="name">
          <el-input
            v-model="queryParams.name"
            placeholder="请输入姓名"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="学号" prop="studentNo">
          <el-input
            v-model="queryParams.studentNo"
            placeholder="请输入学号"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="专业" prop="major">
          <el-select v-model="queryParams.major" placeholder="请选择专业" clearable>
            <el-option
              v-for="major in majorList"
              :key="major"
              :label="major"
              :value="major"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="班级" prop="major">
          <el-select v-model="queryParams.className" placeholder="请选择班级" clearable>
            <el-option
              v-for="className in classList"
              :key="className"
              :label="className"
              :value="className"
            />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>


      <el-form :inline="true" class="demo-form-inline">
        <el-form-item>
          <el-button type="primary" @click="handleAdd" size="mini">新增</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="danger" @click="handleDelete" size="mini">删除</el-button>
        </el-form-item>
      </el-form>
      <el-table :data="tableData" stripe style="width: 100%" @selection-change="handleSelectionChange">
        <el-table-column
          type="selection"
          width="55">
        </el-table-column>
        <el-table-column
          type="index"
          prop="index"
          label="序号"
          width="180">
        </el-table-column>
        <el-table-column
          prop="account"
          label="用户名"
          width="180">
        </el-table-column>
        <el-table-column
          prop="name"
          label="姓名"
          width="180">
        </el-table-column>
        <el-table-column
          prop="avatar"
          label="头像"
          width="180">
          <template slot-scope="scope">
            <img :src="scope.row.avatar" style="width: 100px; height: 100px;">
          </template>
        </el-table-column>
        <el-table-column
          prop="studentNo"
          label="学号"
          width="180">
        </el-table-column>
        <el-table-column
          prop="major"
          label="专业"
          width="180">
        </el-table-column>
        <el-table-column
          prop="className"
          label="班级"
          width="180">
        </el-table-column>
        <el-table-column
          prop="age"
          label="年龄">
        </el-table-column>
        <el-table-column
          prop="gender"
          label="性别">
          <template slot-scope="scope">
            <span v-if="scope.row.gender === 0">女</span>
            <span v-else-if="scope.row.gender === 1">男</span>
            <span v-else>未知</span>
          </template>
        </el-table-column>

        <el-table-column
          align="right">
          <template slot-scope="scope">
            <el-button type="text"
                       size="mini"
                       @click="handleEdit(scope.row)">编辑</el-button>
          </template>
        </el-table-column>

      </el-table>

      <div class="pageCont">
        <el-pagination
          background
          layout="prev, pager, next"
          v-show="total>0"
          :page-size.sync="queryParams.pageSize"
          @current-change="getList"
          :current-page.sync="queryParams.page"
          :total="total">
        </el-pagination>
      </div>

      <el-dialog :title="title" :visible.sync="open" >
        <el-form :model="form" :rules="rules" ref="form">
          <el-form-item label="用户名" label-width="120px" prop="account">
            <el-input v-model="form.account" autocomplete="off" :disabled="flag"></el-input>
          </el-form-item>
          <el-form-item label="姓名" label-width="120px" prop="name">
            <el-input v-model="form.name" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="学号" label-width="120px" prop="studentNo">
            <el-input v-model="form.studentNo" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="专业" label-width="120px" prop="major">
            <el-input v-model="form.major" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="班级" label-width="120px" prop="className">
            <el-input v-model="form.className" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="年龄" label-width="120px">
            <el-input v-model="form.age" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="性别" label-width="120px">
            <el-radio-group v-model="form.gender">
              <el-radio :label="1">男</el-radio>
              <el-radio :label="0">女</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="头像" label-width="120px">
            <el-upload
              ref="upload"
              :limit="1"
              accept=".jpg, .png, .jpeg"
              :action="upload.url"
              :headers="upload.headers"
              :file-list="upload.productFileList"
              :on-progress="handleFileUploadProgress"
              :on-success="imageUrlProductPicSuccess"
              :before-upload="beforeFileUpload"
              list-type="picture-card">
              <i class="el-icon-plus"></i>
              <div slot="tip" class="el-input__tip" style="color:#E6A23C">*建议图片像素：750*420px</div>
            </el-upload>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submit">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </el-dialog>


    </div>

  </div>

</template>

<script>
import {getStudentList,getStudentInfo,addStudent,updateStudent,deleteStudent,getMajorList,getClassList  } from "@/api/student";
import {getToken  } from "@/utils/auth";

export default {
  name: "student",
  data() {
    return {
      showSearch: true,
      open: false,
      title: '',
      queryParams: {
        pageSize:10,
        page:1
      },
      upload: {  // 上传参数
        isUploading: false,  // 是否禁用上传
        headers: {token: getToken()},  // 设置上传的请求头部
        url: process.env.VUE_APP_BASE_API + "/student/uploadFile",  // 上传的地址
        productFileList: [],   // 上传的文件列表
      },
      total:0,
      navId: 0,
      form: {},
      multiple: true,

      tableData: [],
      majorList: [],
      classList: [],
      flag: false,
      // 选中数组
      ids: [],
      rules: {
        account: [
          { required: true,message: '用户名不可为空！', trigger: 'blur' },
        ],
        name: [
          { required: true,message: '姓名不可为空！', trigger: 'blur' },
        ],
        studentNo: [
          { required: true,message: '学号不可为空！', trigger: 'blur' },
          { max: 14, message: '学号不可超过14位', trigger: 'blur' },
        ],
        major: [
          { required: true,message: '专业不可为空！', trigger: 'blur' },
        ],
        className: [
          { required: true,message: '班级不可为空！', trigger: 'blur' },
        ],
      },
    };
  },
  created(){
    this.getList();
    console.log(this.tableData)
  },
  props: {},
  methods: {

    getMajorList(){
      getMajorList().then(response => {
        this.majorList = response.data.majorList;
      });
    },

    getClassList(){
      getClassList().then(response => {
        this.classList = response.data.classList;
      });
    },

    getList() {
      this.getMajorList();
      this.getClassList();
      getStudentList(this.queryParams).then(response => {
        this.tableData = response.data.pages.list;
        this.total = response.data.pages.total;
      });
    },

    cancel() {
      this.open = false;
      this.reset();
    },

    reset() {
      this.upload.productFileList = [],   // 上传的文件列表
      this.form = {
        id: null,
        name: null,
        account: null,
        password: null,
      };
    },


    handleQuery() {
      this.queryParams.page = 1;
      this.getList();
    },

    resetQuery() {
      this.queryForm = {};
      this.queryParams = {
          pageSize:10,
          page:1
      },
      this.handleQuery();
    },


    handleAdd() {
      this.reset();
      this.open = true;
      this.flag = false;
      this.title = "添加";
    },

    handleEdit(row) {
      this.reset();
      this.flag = true;
      const id = row.id
      getStudentInfo(id).then(response => {
        this.form = response.data.userInfo;
        if (this.form.avatar) {
          this.upload.productFileList = [{name: 'default', url: this.form.avatar}];
        }
        this.open = true;
        this.title = "编辑";
      });
    },

    submit(){
      this.$refs.form.validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateStudent(this.form).then(response => {
              this.$message.success("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addStudent(this.form).then(response => {
              this.$message.success("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });

    },

    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.multiple = !selection.length
    },

    handleDelete(row) {
      const delId = row.id || this.ids;
      if (this.multiple){
        this.$message({
          type: 'warning',
          message: '请选择需要删除的记录'
        });
        return;
      }
      this.$confirm('此操作将永久删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        return deleteStudent(delId);
      }).then(() => {
        this.getList();
        this.$message({
          type: 'success',
          message: '删除成功!'
        });
      }).catch(() => {
        this.$message({
          type: 'warning',
          message: '已取消删除'
        });
      });
    },

    /** 文件上传前的判断 */
    beforeFileUpload(file) {
      const isJPG = file.type === 'image/jpg';
      const isJPEG = file.type === 'image/jpeg';
      const isPNG = file.type === 'image/png';
      const isSize = file.size / 1024 / 1024 < 5;

      if (!isJPG && !isJPEG && !isPNG) {
        this.$message.error('上传图片只能是 .JPG/.JPEG/.PNG 格式!');
      }
      if (!isSize) {
        this.$message.error('上传图片大小不能超过 5MB!');
      }
      return (isJPG || isJPEG || isPNG) && isSize;
    },
    /** 文件上传中处理 */
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    /** 文件上传成功处理 */
    imageUrlProductPicSuccess(response, file, fileList) {
      this.upload.isUploading = false;
      this.form.avatar = response.data.url;
      this.$message.success(response.message);
    }

  },
};
</script>

<style scoped>
  .pageCont{
    width: 100%;
    display: flex;
    justify-content: center;
    margin-top: 50px;
  }
</style>
